#include "gpio_sysfs.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int gpio_open(gpio_t *gpio, int pin, const char *direction)
{
    // 导出
    FILE *export_fp = fopen("/sys/class/gpio/export", "w");
    if (!export_fp)
        return -1;
    fprintf(export_fp, "%d", pin);
    fclose(export_fp);

    // 构建路径
    snprintf(gpio->value_path, sizeof(gpio->value_path),
             "/sys/class/gpio/gpio%d/value", pin);
    snprintf(gpio->direction_path, sizeof(gpio->direction_path),
             "/sys/class/gpio/gpio%d/direction", pin);

    // 设置方向
    FILE *dir_fp = fopen(gpio->direction_path, "w");
    if (!dir_fp)
        return -1;
    fprintf(dir_fp, "%s", direction);
    fclose(dir_fp);

    // 打开 value 文件用于写（保持打开）
    gpio->value_fp = fopen(gpio->value_path, "w");
    if (!gpio->value_fp)
        return -1;

    gpio->pin = pin;
    return 0;
}

int gpio_write(gpio_t *gpio, int value)
{
    if (!gpio->value_fp)
        return -1;
    fprintf(gpio->value_fp, "%d", !!value); // 强制 0/1
    fflush(gpio->value_fp);
    return 0;
}

int gpio_read(gpio_t *gpio)
{
    FILE *fp = fopen(gpio->value_path, "r");
    if (!fp)
        return -1;
    int val;
    fscanf(fp, "%d", &val);
    fclose(fp);
    return val;
}

int gpio_close(gpio_t *gpio)
{
    if (gpio->value_fp)
        fclose(gpio->value_fp);
    FILE *unexport_fp = fopen("/sys/class/gpio/unexport", "w");
    if (!unexport_fp)
        return -1;
    fprintf(unexport_fp, "%d", gpio->pin);
    fclose(unexport_fp);
    return 0;
}
